package tech.runchen.gz5055.oms.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.runchen.gz5055.oms.common.annotation.RequiresPermissions;
import tech.runchen.gz5055.oms.common.annotation.SysLog;
import tech.runchen.gz5055.oms.common.base.AbstractController;
import tech.runchen.gz5055.oms.common.constant.Constant;
import tech.runchen.gz5055.oms.common.enums.BusinessType;
import tech.runchen.gz5055.oms.common.enums.UserType;
import tech.runchen.gz5055.oms.common.utils.Result;
import tech.runchen.gz5055.oms.common.utils.StringUtils;
import tech.runchen.gz5055.oms.common.utils.redis.RedisUtils;
import tech.runchen.gz5055.oms.modules.system.service.MqttSender;

/**
 * @author zzj
 */
@Api(tags = "管理平台 - 机器人模块")
@RestController
@RequestMapping("/sys/robot")
public class SysRobotController extends AbstractController {

    @Autowired
    private MqttSender mqttSender;
    @Autowired
    private RedisUtils redisUtils;

    @SysLog(title = "呼叫机器人", businessType = BusinessType.OPERATE)
    @ApiOperation("呼叫机器人")
    @RequiresPermissions(value = {UserType.SPD, UserType.NURSE})
    @GetMapping("/call")
    public Result call() throws InterruptedException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "call");
        mqttSender.sendToMqtt("RunChen/SM/Call/pub", jsonObject.toJSONString());
        Thread.sleep(1000L);
        String payload = redisUtils.getCacheObject(Constant.MQTT_SM_CALL_ROBOT_KEY);
        if (StringUtils.isBlank(payload)) {
            Thread.sleep(2000L);
            payload = redisUtils.getCacheObject(Constant.MQTT_SM_CALL_ROBOT_KEY);
        }
        if (StringUtils.isNotBlank(payload)) {
            JSONObject object = JSON.parseObject(payload);
            redisUtils.deleteObject(Constant.MQTT_SM_CALL_ROBOT_KEY);
            return Result.success(object.getString("msg"), object);
        } else {
            return Result.error("呼叫请求未得到响应");
        }
    }

}
